package com.headline.controller;


import com.headline.common.Common;
import com.headline.common.Log;
import com.headline.common.PageObject;
import com.headline.model.SpiderNewsInfoEntity;
import com.headline.service.SpiderNewsInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;


/**
 * Created by Administrator on 2016/10/20.
 */
@Controller
@RequestMapping(value = "/article")
public class ArticleController {

    //    @Autowired
//    SpiderNewsInfoRepository spiderNewsInfoRepository;


    Log log = Log.getLogger();
    SpiderNewsInfoService spiderNewsInfoService = new SpiderNewsInfoService();

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(HttpServletRequest request, ModelMap modelMap) {
        String pageNumberStr = request.getParameter("page");
        if (pageNumberStr == null || "".equals(pageNumberStr)) {
            pageNumberStr = "1";
        }

        int pageNumber = Integer.parseInt(pageNumberStr);
        int pageSize = 30;
        PageObject page = spiderNewsInfoService.queryPage(pageNumber, pageSize);
        modelMap.addAttribute("newsList", page.getDatasource());
        modelMap.addAttribute("totalPageNumber", page.getAbsolutePage());
        modelMap.addAttribute("pageSize", pageSize);
        modelMap.addAttribute("pageNumber", pageNumber);
        return "article/list";
    }

    @RequestMapping(value = "show/{id}", method = RequestMethod.GET)
    public String showNews(@PathVariable("id") int id, ModelMap modelMap) {
        SpiderNewsInfoEntity spiderNewsInfoEntity = spiderNewsInfoService.querySpiderNewsInfoById(id);
        if (spiderNewsInfoEntity != null) {
            try {
                spiderNewsInfoEntity.setPublishtime(Common.GetSqlDate(spiderNewsInfoEntity.getPublishtime().toString().substring(0, 10)));
            } catch (ParseException e) {
                e.printStackTrace();
                log.logger.error("showNews，时间转换失败" + e.getMessage());
            }

        }
        modelMap.addAttribute("news", spiderNewsInfoEntity);
        return "article/detail";
    }


    @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
    public String deleteNews(@PathVariable("id") int id) {
        spiderNewsInfoService.deleteSpiderNewsInfoById(id);
        log.logger.error("删除一条文章Id:" + id);
        return "redirect:/article/list";
    }



}
